<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import ProfileCard from '@/components/Profile/ProfileCard.vue'
const searchQuery = ref('')
const selectedCategory = ref('')
const currentPage = ref(1)
const itemsPerPage = ref(12)
const isScrolled = ref(false)

const router = useRouter()
// 监听滚动事件
const handleScroll = () => {
  isScrolled.value = window.scrollY > 50
}

onMounted(() => {
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

// 模拟博客数据
const blogPosts = ref([
  {
    id: 1,
    title: 'Vue 3 组合式 API 深度解析',
    summary:
      '深入探讨 Vue 3 组合式 API 的核心概念、使用技巧和最佳实践，帮助开发者更好地理解和应用这一强大的特性。',
    content: '...',
    author: '张三',
    publishDate: '2024-01-15',
    category: '前端开发',
    tags: ['Vue', 'JavaScript', '前端'],
    coverImage: 'https://picsum.photos/400/250?random=1',
    comments: '8 条评论',
    views: 1234
  },
  {
    id: 2,
    title: 'TypeScript 高级类型系统详解',
    summary:
      '全面介绍 TypeScript 的高级类型系统，包括泛型、条件类型、映射类型等高级特性，提升代码质量和开发效率。',
    content: '...',
    author: '李四',
    publishDate: '2024-01-12',
    category: '编程语言',
    tags: ['TypeScript', '类型系统', '编程'],
    coverImage: 'https://picsum.photos/400/250?random=2',
    comments: '12 条评论',
    views: 856
  },
  {
    id: 3,
    title: '现代 CSS 布局技术完全指南',
    summary: '从 Flexbox 到 Grid，从传统布局到现代 CSS 技术，全面掌握现代网页布局的核心技能。',
    content: '...',
    author: '王五',
    publishDate: '2024-01-10',
    category: '前端开发',
    tags: ['CSS', '布局', '响应式'],
    coverImage: 'https://picsum.photos/400/250?random=3',
    comments: '15 条评论',
    views: 2103
  },
  {
    id: 4,
    title: 'Node.js 性能优化实践',
    summary:
      '深入分析 Node.js 应用的性能瓶颈，提供实用的优化策略和工具，让你的应用跑得更快更稳定。',
    content: '...',
    author: '赵六',
    publishDate: '2024-01-08',
    category: '后端开发',
    tags: ['Node.js', '性能优化', '后端'],
    coverImage: 'https://picsum.photos/400/250?random=4',
    comments: '10 条评论',
    views: 1456
  },
  {
    id: 5,
    title: '微服务架构设计模式',
    summary: '探讨微服务架构的核心设计模式，包括服务拆分、数据管理、通信机制等关键问题。',
    content: '...',
    author: '孙七',
    publishDate: '2024-01-05',
    category: '架构设计',
    tags: ['微服务', '架构', '设计模式'],
    coverImage: 'https://picsum.photos/400/250?random=5',
    comments: '18 条评论',
    views: 987
  },
  {
    id: 6,
    title: 'Docker 容器化部署最佳实践',
    summary: '从基础概念到生产环境部署，全面掌握 Docker 容器化技术的核心要点和最佳实践。',
    content: '...',
    author: '周八',
    publishDate: '2024-01-03',
    category: 'DevOps',
    tags: ['Docker', '容器化', '部署'],
    coverImage: 'https://picsum.photos/400/250?random=6',
    comments: '14 条评论',
    views: 1678
  }
])

// 获取所有分类
const categories = computed(() => {
  const cats = [...new Set(blogPosts.value.map((post) => post.category))]
  return ['全部', ...cats]
})

// 过滤后的博客列表
const filteredPosts = computed(() => {
  let filtered = blogPosts.value

  // 按搜索关键词过滤
  if (searchQuery.value) {
    filtered = filtered.filter(
      (post) =>
        post.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        post.summary.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        post.tags.some((tag) => tag.toLowerCase().includes(searchQuery.value.toLowerCase()))
    )
  }

  // 按分类过滤
  if (selectedCategory.value && selectedCategory.value !== '全部') {
    filtered = filtered.filter((post) => post.category === selectedCategory.value)
  }

  return filtered
})

// 分页后的博客列表
const paginatedPosts = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value
  const end = start + itemsPerPage.value
  return filteredPosts.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredPosts.value.length / itemsPerPage.value)
})

const goToBlog = (id: number) => {
  router.push(`/blog/${id}`)
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const getCategoryColor = (category: string) => {
  const colorMap: { [key: string]: string } = {
    前端开发: 'blue',
    后端开发: 'green',
    编程语言: 'purple',
    架构设计: 'orange',
    DevOps: 'teal'
  }
  return colorMap[category] || 'grey'
}

// 侧边栏数据
const latestPosts = computed(() => {
  return blogPosts.value.slice(0, 5).map((post) => ({
    title: post.title,
    date: post.publishDate,
    category: post.category
  }))
})

const latestComments = ref([
  { author: 'Frankie', content: '有没有虚拟机ISO文件可以下载', date: '2025-09-03' },
  { author: 'Peter', content: '非常有用 👍', date: '2025-09-02' },
  {
    author: 'PeterJXL',
    content: '这百度看图自动设为默认软件的行为,也太恶心了 🤮',
    date: '2025-09-02'
  },
  { author: 'iMaeGoo', content: '已更新贵站友链', date: '2025-09-02' }
])
</script>

<template>
  <!-- 主要内容区域 -->
  <v-main class="d-flex flex-fill overflow-y-auto justify-center" style="flex-wrap: wrap">
    <!-- 左侧个人信息栏 -->
    <v-col cols="12" sm="5" md="4" lg="3" xl="2" class="d-lg-flex mb-4 py-7 pl-4 pr-0">
      <ProfileCard />
    </v-col>
    <v-col cols="12" sm="7" md="8" lg="7" xl="6">
      <v-container max-width="100%" class="pa-4 ml-0 mx-0">
        <!-- 搜索和筛选区域 -->
        <v-row class="mb-6 justify-center">
          <v-col cols="12" sm="8" md="8" lg="9">
            <v-text-field
              :density="'comfortable'"
              v-model="searchQuery"
              placeholder="搜索博客..."
              prepend-inner-icon="mdi-magnify"
              variant="outlined"
              clearable
              hide-details
              class="search-field neu-input"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="4" md="4" lg="3">
            <v-select
              :density="'comfortable'"
              v-model="selectedCategory"
              :items="categories"
              placeholder="选择分类"
              variant="outlined"
              hide-details
              clearable
              class="neu-input"
            ></v-select>
          </v-col>
        </v-row>

        <!-- 博客列表 -->
        <v-row class="justify-center">
          <v-col
            v-for="post in paginatedPosts"
            :key="post.id"
            cols="12"
            sm="12"
            md="6"
            lg="4"
            xl="4"
          >
            <v-card
              class="blog-card h-100 d-flex flex-column"
              elevation="1"
              hover
              @click="goToBlog(post.id)"
            >
              <!-- 博客封面图片 -->
              <v-img :src="post.coverImage" :aspect-ratio="16 / 9" cover class="blog-cover">
                <template v-slot:placeholder>
                  <v-row class="fill-height ma-0" align="center" justify="center">
                    <v-progress-circular indeterminate color="primary"></v-progress-circular>
                  </v-row>
                </template>
              </v-img>

              <!-- 博客内容 -->
              <v-card-text class="flex-grow-1 d-flex flex-column py-1">
                <!-- 分类标签 -->
                <!-- <div class="mb-2">
                    <v-chip :color="getCategoryColor(post.category)" size="small" variant="tonal">
                      {{ post.category }}
                    </v-chip>
                  </div> -->

                <!-- 博客标题 -->
                <h3 class="text-h6 font-weight-bold mb-2 text-truncate">
                  {{ post.title }}
                </h3>

                <!-- 博客摘要 -->
                <p class="text-body-2 text-grey-darken-1 mb-2 flex-grow-1 ellipsis">
                  {{ post.summary }}
                </p>

                <!-- 作者和发布时间 -->
                <div class="d-flex align-center justify-space-between text-caption text-grey">
                  <div class="d-flex align-center">
                    <v-icon size="small" class="mr-1">mdi-account</v-icon>
                    {{ post.author }}
                  </div>
                  <div class="d-flex align-center">
                    <v-icon size="small" class="mr-1">mdi-calendar</v-icon>
                    {{ formatDate(post.publishDate) }}
                  </div>
                </div>
              </v-card-text>

              <!-- 博客底部信息 -->
              <v-card-actions class="px-4 py-1" style="min-height: 40px">
                <div class="d-flex align-center text-caption text-grey">
                  <v-icon size="small" class="mr-1">mdi-comment</v-icon>
                  {{ post.comments }}
                </div>
                <v-spacer></v-spacer>
                <div class="d-flex align-center text-caption text-grey">
                  <v-icon size="small" class="mr-1">mdi-eye</v-icon>
                  {{ post.views }} 次阅读
                </div>
              </v-card-actions>
            </v-card>
          </v-col>
        </v-row>

        <!-- 分页组件 -->
        <v-row v-if="totalPages > 1" class="mt-6 justify-center">
          <v-col cols="12" sm="8" md="6" lg="4" class="d-flex justify-center">
            <v-pagination
              v-model="currentPage"
              :length="totalPages"
              :total-visible="7"
              color="primary"
            ></v-pagination>
          </v-col>
        </v-row>

        <!-- 无结果提示 -->
        <v-row v-if="filteredPosts.length === 0">
          <v-col cols="12" class="text-center py-12">
            <v-icon size="64" color="grey-lighten-1" class="mb-4">mdi-magnify-close</v-icon>
            <h3 class="text-h5 text-grey-lighten-1 mb-2">未找到相关博客</h3>
            <p class="text-body-1 text-grey-lighten-1">请尝试其他搜索关键词或分类</p>
          </v-col>
        </v-row>
      </v-container>
    </v-col>
    <!-- 右侧边栏 -->
    <v-col cols="12" sm="12" md="12" lg="10" xl="8" class="mx-0">
      <!-- 最新文章 -->
      <v-card class="mb-4" elevation="2">
        <v-card-title class="text-h6">最新文章</v-card-title>
        <v-card-text class="pt-0">
          <div
            v-for="(post, index) in latestPosts"
            :key="index"
            class="latest-post-item d-flex flex-column py-2"
            :class="{ 'border-b': index < latestPosts.length - 1 }"
          >
            <div class="text-body-2 font-weight-medium mb-1">{{ post.title }}</div>
            <div class="d-flex justify-space-between align-center">
              <v-chip size="x-small" variant="tonal" :color="getCategoryColor(post.category)">
                {{ post.category }}
              </v-chip>
              <span class="text-caption text-grey">{{ formatDate(post.date) }}</span>
            </div>
          </div>
        </v-card-text>
      </v-card>

      <!-- 最新评论 -->
      <v-card elevation="2">
        <v-card-title class="text-h6">最新评论</v-card-title>
        <v-card-text class="pt-0">
          <div
            v-for="(comment, index) in latestComments"
            :key="index"
            class="latest-comment-item py-2"
            :class="{ 'border-b': index < latestComments.length - 1 }"
          >
            <div class="text-body-2 mb-1">{{ comment.content }}</div>
            <div class="d-flex justify-space-between align-center">
              <span class="text-caption text-grey">{{ comment.author }}</span>
              <span class="text-caption text-grey">{{ formatDate(comment.date) }}</span>
            </div>
          </div>
        </v-card-text>
      </v-card>
    </v-col>
  </v-main>
</template>

<style scoped>
.ellipsis {
  --lines: 2; /* 修改此变量即可控制行数 */
  display: -webkit-box;
  -webkit-line-clamp: var(--lines);
  line-clamp: var(--lines);
  -webkit-box-orient: vertical;
  overflow: hidden;
}
/* 搜索框样式 */
.search-field {
  max-width: 100%;
}

/* 容器样式优化 */
.v-container {
  padding-left: 24px;
  padding-right: 24px;
}

/* 响应式容器调整 */
@media (max-width: 600px) {
  .v-container {
    padding-left: 16px;
    padding-right: 16px;
  }
}

/* 博客卡片样式 */
.blog-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.blog-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
}

/* 博客封面图片样式 */
.blog-cover {
  position: relative;
  overflow: hidden;
}

.blog-cover::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    45deg,
    rgba(0, 0, 0, 0.1) 0%,
    transparent 50%,
    rgba(0, 0, 0, 0.1) 100%
  );
  opacity: 0;
  transition: opacity 0.3s ease;
}

.blog-card:hover .blog-cover::after {
  opacity: 1;
}

/* 标签样式 */
.v-chip {
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 分页组件样式 */
.v-pagination {
  margin-top: 2rem;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .v-card-text {
    padding: 16px;
  }

  .blog-card {
    margin-bottom: 16px;
  }
}

/* 加载动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.blog-card {
  animation: fadeInUp 0.6s ease-out;
}

/* 为不同位置的卡片添加延迟动画 */
.blog-card:nth-child(1) {
  animation-delay: 0.1s;
}
.blog-card:nth-child(2) {
  animation-delay: 0.2s;
}
.blog-card:nth-child(3) {
  animation-delay: 0.3s;
}
.blog-card:nth-child(4) {
  animation-delay: 0.4s;
}
.blog-card:nth-child(5) {
  animation-delay: 0.5s;
}
.blog-card:nth-child(6) {
  animation-delay: 0.6s;
}

/* 无结果状态样式 */
.v-icon.mdi-magnify-close {
  opacity: 0.6;
}
</style>
